package com.example.smartcity.ui.AcNews

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.R
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.ActivitySeekBinding
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.home.HomeViewModel
import com.example.smartcity.ui.home.adapter.NewSHotRecyclerViewAdapter
import com.example.smartcity.ui.home.model.NewSRecyclerViewEntity

/**
 * 搜索模块
 */
class SeekActivity : AppCompatActivity() {

    private val viewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    private lateinit var mbinding: ActivitySeekBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mbinding = ActivitySeekBinding.inflate(layoutInflater)
        setContentView(mbinding.root)
        title = "搜索信息"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 接收数据
        val content = intent.getStringExtra("content")

        // 实现模糊查询
        content?.let {
            SeekNews(it)
        }
    }

    /**
     * 模糊查询
     */
    private fun SeekNews(contend: String) {
        // 临时存储新闻
        val array = ArrayList<NewSRecyclerViewEntity>()

        val re = mbinding.SeekRecyclerView
        val layout = LinearLayoutManager(this)
        re.layoutManager = layout
        val adapter = NewSHotRecyclerViewAdapter(array)
        re.adapter = adapter

        viewModel.newsAll("")
        viewModel.newSLiveDataAll.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if(body != null){
                viewModel.newsAll.clear()
                viewModel.newsAll.addAll(body)
            }

            for (i in viewModel.newsAll){
                // 遍历查找字符串
                contend.forEach { a ->
                    i.title.forEach {
                        if (a == it){
                            array.add(NewSRecyclerViewEntity(
                                SmartCityApplication.url + i.cover,
                                i.title,
                                Html.fromHtml(i.content).toString(),
                                i.commentNum.toString(),
                                i.publishDate
                            ))

                            // 刷新
                            adapter.notifyItemChanged(array.size)
                        }
                    }
                }
            }
        })
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        this@SeekActivity.finish()
        return super.onOptionsItemSelected(item)
    }
}